<template>
  <div class="player-container">

    <audio ref="audio"
           @ended="onAudioEnd"
           :src="computedCurrentAudioIndex"
           :autoplay="autoPlay">
      您的浏览器不支持此播放器。
    </audio>

    <div class="book-cover" :style="`background-image: url(${audioData.backImg});`"></div>

    <p class="title">{{audioData.title}}</p>

    <p class="subtitle">{{audioData.summary}}</p>

    <div class="process-bar">
      <div class="process-lines"
           ref="process"
           @click="onProcess($event.pageX)"
           @touchstart="onProcessTouchStart"
           @touchmove="onProcessTouchMove"
           @touchend="onProcessTouchEnd">
        <div class="total-line"></div>
        <div class="current-line" :style="`width: ${computedProgress}%;`">
          <div class="loading" v-if="state.isLoading"></div>
        </div>
      </div>
      <div class="data">
        <div>{{computedCurrentTime}}</div>
        <div>{{computedDuration}}</div>
      </div>
    </div>

    <div class="control-bar">

      <div class="pre-seconds">
        <div class="btn-pre-seconds" @click="changeCurrentTime(-15)"></div>
      </div>

      <div class="control-core">
        <div class="btn-pre" @click="changeCurrentAudioIndex(-1)"></div>
        <div class="btn-play" @click="audioToggle">
          <img :src="computedPlaySrc" alt="play" />
        </div>
        <div class="btn-next" @click="changeCurrentAudioIndex(1)"></div>
      </div>

      <div class="next-seconds">
        <div class="btn-next-seconds" @click="changeCurrentTime(15)"></div>
      </div>
      <com-dialog v-if="showDialog" :dialogConent="dialogConent" @leftBtn="cancelBtn" @rightBtn="sureBtn"></com-dialog>
    </div>
  </div>
</template>
<script>
  import comDialog from '@/components/comDialog.vue'
  import { post } from '../../../../util/http.js'
  export default {

    name: 'player',

    mounted() {
      const that = this
      post('http://dhapi3.rz158.com/mindMain/getMindMainByIdV3',{
        mid: this.$route.query.pid
      }).then(res => {
        if(res.code == 0) {
            this.audioData = res.result.mindDetailPlayVo
            this.computedCurrentAudioIndex =  this.audioData.audioUrl
        }
      })
      that.state.isPlaying = that.autoPlay
      that.$refs.audio.addEventListener('canplay', () => {
        that.duration = that.$refs.audio.duration
        if (this.$route.query.type=0) {
          this.limitTime = 300
        }
        if (this.$route.query.type=1) {
          this.limitTime = this.duration
        }
        if (that.autoPlay && !that.state.autoPlayed) {
          that.state.autoPlayed = true
          that.startAudioWatch()
        }
      })
      that.$refs.audio.addEventListener('playing', () => {
        that.state.isLoading = false
      })
      that.$refs.audio.addEventListener('waiting', () => {
        that.state.isLoading = true
      })
      // 页面聚焦恢复定时器
      window.addEventListener('focus', () => {
        if (that.state.isPlaying) {
          that.startAudioWatch()
        }
      })
      // 页面失焦清除定时器
      window.addEventListener('blur', () => {
        clearInterval(that.currentTimeWatcher)
      })
      // 禁用触摸滑动
      document.addEventListener('touchmove', e => {
        e.preventDefault()
      }, {passive: false})
      document.addEventListener('DOMMouseScroll', e => {
        e.preventDefault()
      }, {passive: false})
    },
    components: {comDialog},
    data() {
      return {
        audioData: '',
        autoPlay: false,
        state: {
          isPlaying: false, // 播放状态
          isTouching: false, // 用户是否正在连续触摸屏幕
          isLoading: false, // 音频是否因为下一帧缓冲而暂停
          autoPlayed: false, // 是否已经自动播放过
        },
        playSrc: require('@/assets/img/media-play.svg'),
        pauseSrc: require('@/assets/img/media-pause.svg'),
        duration: '', // 当前音源播放总时长
        currentTime: '', // 当前音源播放时刻
        currentTimeWatcher: '', // 用于更新当前播放时刻
        currentAudioIndex: 0, // 当前播放音源序号
        currentX: 0, // 当前触摸位置X坐标
        showDialog: false,
        dialogConent: {
          title: ' 试听结束,请购买成为VIP年会员',
          left: '返回',
          right: '开通VIP'
        },
        limitTime: 300,
        computedCurrentAudioIndex: ''
      }
    },
    watch: {
      currentTime (cur, old) {
        if (cur >= this.limitTime) {
          this.audioPause()
          this.showDialog = true
        }
      },
      computedCurrentAudioIndex (cur, old) {
        console.log(this.audioData.audioUrl)
        return this.audioData.audioUrl
      }
    },
    computed: {

      computedPlaySrc() {
        return this.state.isPlaying ? this.pauseSrc : this.playSrc
      },

      computedCurrentTime() {
        return this.formatTime(
          this.state.isTouching
            ? this.computedCurrentProcessRate * this.duration
            : this.currentTime
        )
      },

      computedDuration() {
        return this.formatTime(this.duration)
      },

      computedProgress() {
        return this.state.isTouching
          ? this.computedCurrentProcessRate * 100
          : this.currentTime && this.duration
            ? this.currentTime / this.duration * 100
            : 0
      },


      computedCurrentProcessRate() {
        const {offsetLeft, offsetWidth} = this.$refs.process
        return (this.currentX - offsetLeft) / offsetWidth
      },
    },

    methods: {
       cancelBtn () {
          setTimeout (() => {
              this.showDialog = false
          }, 200)
      },
      sureBtn () {
          
      },
      formatTime(time) {
        const {floor} = Math
        let s, m, h
        s = m = h = 0
        if (time) {
          s = floor(time % 60)
          m = floor(time / 60)
          h = floor(time / (60 ** 2))
        }
        const s_string = s < 10 ? '0' + s : s.toString()
        const m_string = m < 10 ? '0' + m : m.toString()
        if (h === 0) {
          return [m_string, s_string].join(':')
        } else {
          const h_string = h < 10 ? '0' + h : h.toString()
          return [h_string, m_string, s_string].join(':')
        }
      },

      changeCurrentTime(second) {
        this.$refs.audio.currentTime += second
        if (this.$refs.audio.currentTime > 0) {
          this.currentTime = this.$refs.audio.currentTime
        }
      },

      changeCurrentAudioIndex(change) {
        this.currentAudioIndex = // 这是毅种循环
          (this.currentAudioIndex + change + this.audioData.length) % this.audioData.length
        this.state.isPlaying = this.autoPlay
      },

      startAudioWatch() {
        const that = this
        that.stopAudioWatch()
        that.currentTimeWatcher = setInterval(() => {
          that.currentTime = that.$refs.audio.currentTime
        }, 1000)
      },

      stopAudioWatch() {
        clearInterval(this.currentTimeWatcher)
      },

      audioPlay() {
        this.$refs.audio.play()
        this.state.isPlaying = true
        this.startAudioWatch()
      },

      audioPause() {
        this.$refs.audio.pause()
        this.state.isPlaying = false
        this.stopAudioWatch()
      },

      audioToggle() {
        this.state.isPlaying && (this.currentTime <= this.limitTime) ? this.audioPause() : this.audioPlay()
      },

      onAudioEnd() {
        this.changeCurrentAudioIndex(1)
        this.state.isPlaying = this.autoPlay
      },

      onProcess(x) {
        const {offsetLeft, offsetWidth} = this.$refs.process
        if (offsetLeft <= x && x <= offsetLeft + offsetWidth) {
          const {audio} = this.$refs
          const rate = (x - offsetLeft) / offsetWidth
          this.currentTime = audio.currentTime = audio.duration * rate
        }
      },

      onProcessTouchStart(e) {
        this.currentX = e.changedTouches[0].clientX
        this.state.isTouching = true
      },

      onProcessTouchMove(e) {
        const x = e.changedTouches[0].clientX
        const {offsetLeft, offsetWidth} = this.$refs.process
        if (offsetLeft <= x && x <= offsetLeft + offsetWidth) {
          this.currentX = x
        }
      },

      onProcessTouchEnd(e) {
        this.state.isTouching = false
        this.onProcess(e.changedTouches[0].clientX)
      },
    }
  }
</script>

<style lang="stylus" scoped>

  *
    box-sizing border-box

  side_control_size = 0.4rem

  @keyframes breath
    50%
      width 0.25rem
      height 0.25rem
      background-color rgba(190, 230, 231, 0.4)
    100%
      width 0.28rem
      height 0.28rem
      background-color rgba(190, 230, 231, 0.8)

  @keyframes rotate
    100%
      transform translate(50%, -50%) rotate(1turn)

  handleIcon()
    background-size contain
    width side_control_size
    height @width

  flex_normal()
    display flex
    flex-direction row
    justify-content center
    align-items center

  .player-container
    max-width 750px
    overflow auto
    text-align center
    .book-cover
      margin 1.4rem auto 0.9rem auto
      width 3.03rem
      height 4.5rem
      background-repeat no-repeat
      background-size contain
      background-position center center
    .title
      font-size 0.32rem
      color #282828
      margin-bottom 1em
    .subtitle
      font-size 0.24rem
      color #707070
      margin-bottom 0.6rem
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      padding: 0rem 1rem;
    .process-bar
      padding 0 0.6rem
      margin-bottom 0.65rem
      .process-lines
        position relative
        margin 0.1rem 0
        .total-line
          height 1px
          background-color #ccc
          z-index 1
        .current-line
          position absolute
          left 0
          top 0
          height 1px
          background-color #29abae
          z-index 3
          width 10%
          &::before
            content ''
            position absolute
            right 0
            top 0
            transform translate(50%, -50%)
            width 0.28rem
            height @width
            background-color rgba(190, 230, 231, 0.8)
            border-radius 50%
            animation breath ease-in-out 3s infinite
          &::after
            content ''
            position absolute
            right 0
            top 0
            width 0.18rem
            height @width
            background-color #29abae
            border-radius 50%
            transform translate(50%, -50%)
          .loading
            position absolute
            transform translate(50%, -50%) rotate(0turn)
            z-index 10
            background url("../../../assets/img/loading.svg") center center no-repeat
            background-size 70%
            right  0
            top 0
            border-radius 50%
            width 0.18rem
            height @width
            animation rotate linear 5s infinite

      .data
        color #707070
        font-size 0.2rem
        display flex
        flex-direction row
        justify-content space-between
        align-items center
    .control-bar
      flex_normal()
      margin-bottom 1rem
      .pre-seconds
        display flex
        flex 4
        justify-content center
        .btn-pre-seconds
          background url("../../../assets/img/15-pre.png") no-repeat center center
          handleIcon()
      .next-seconds
        display flex
        flex 4
        justify-content center
        .btn-next-seconds
          background url("../../../assets/img/15-next.png") no-repeat center center
          handleIcon()
      .control-core
        flex_normal()
        flex 5
        justify-content space-between
        .btn-pre
          background url("../../../assets/img/media-previous.svg")
          handleIcon()
        .btn-next
          background url("../../../assets/img/media-next.svg")
          handleIcon()
        .btn-play
          border 0.04rem solid #282828
          padding 0.2rem
          border-radius 50%
          flex_normal()
          img
            width 0.4rem
</style>